package com.ghy.springredis.client.upgrade;

/**
 * @author: 卢佳新
 * @version: v1.0
 * @description: com.ghy.springredis.client.upgrade
 * @date:2022/6/11 13:35
 * @Motto 不积跬步，无以至千里；不积小流，无以成江海。
 */
public class CustomerRedisClient {

    private CustomerRedisClientSocket customerRedisClientSocket;

    public CustomerRedisClient(String host,int port,String password) {
        customerRedisClientSocket=new CustomerRedisClientSocket(host,port,password ("AUTH",password));

    }
    public String password(String key,String value){
        convertToCommand(null,key.getBytes(),value.getBytes());
        return convertToCommand(null,key.getBytes(),value.getBytes());
    }

    public String set(String key,String value){
        customerRedisClientSocket.send(convertToCommand(CommandConstant.CommandEnum.SET,key.getBytes(),value.getBytes()));
        return customerRedisClientSocket.read(); //在等待返回结果的时候，是阻塞的
    }

    public String get(String key){
        customerRedisClientSocket.send(convertToCommand(CommandConstant.CommandEnum.GET,key.getBytes()));
        return customerRedisClientSocket.read();
    }

    public static String convertToCommand(CommandConstant.CommandEnum commandEnum,byte[]... bytes){

        StringBuilder stringBuilder=new StringBuilder();

        if (commandEnum==null){
            stringBuilder.append(CommandConstant.START).append(bytes.length).append(CommandConstant.LINE);
        }else{
            stringBuilder.append(CommandConstant.START).append(bytes.length+1).append(CommandConstant.LINE);
            stringBuilder.append(CommandConstant.LENGTH).append(commandEnum.toString().length()).append(CommandConstant.LINE);
            stringBuilder.append(commandEnum.toString()).append(CommandConstant.LINE);
        }

        for (byte[] by:bytes){
            stringBuilder.append(CommandConstant.LENGTH).append(by.length).append(CommandConstant.LINE);
            stringBuilder.append(new String(by)).append(CommandConstant.LINE);
        }

        return stringBuilder.toString();
    }
}
